//
//  WMEArticleFirstViewController.m
//  everyDay_duiTang
//
//  Created by 恩叔 on 16/3/4.
//  Copyright © 2016年 enshu. All rights reserved.
//

#import "WMEArticleFirstViewController.h"
#import "WMEArticleModel.h"
#import "WMEArticleFirstCollectionViewCell.h"
#import "WMEArticleInformationViewController.h"
#import <AFNetworking.h>
#import <Masonry.h>
#import <MJRefresh.h>

@interface WMEArticleFirstViewController ()<UICollectionViewDataSource, UICollectionViewDelegate>
@property (nonatomic, retain)UICollectionView *collectionView;/**<主collection*/
@property (nonatomic, retain)NSNumber *next;
@property (nonatomic, retain)NSMutableArray *dataArr;
@property (nonatomic, retain)UILabel *label;
@end

@implementation WMEArticleFirstViewController
- (void)dealloc
{
    [_collectionView release];
    [_next release];
    [_dataArr release];
    [_label release];
    [super dealloc];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationItem.title = @"专栏";
    [self createCollectionView];
    [self data];
    [self refreshFunction];
}

#pragma mark -创建collectionView
- (void)createCollectionView
{
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    layout.itemSize = CGSizeMake((WIDTH - 60) / 2, ((WIDTH - 80) / 2));
    layout.minimumInteritemSpacing = 20;
    layout.minimumLineSpacing = 20;
    layout.sectionInset = UIEdgeInsetsMake(20, 20, 20, 20);
    
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT - 64) collectionViewLayout:layout];
    _collectionView.backgroundColor = [UIColor colorWithRed:236/255.0 green:236/255.0 blue:236/255.0 alpha:1];
    _collectionView.dataSource = self;
    _collectionView.delegate = self;
//    _collectionView.contentInset = UIEdgeInsetsMake(40, 0, 0, 0);
    
//    self.label = [[UILabel alloc] initWithFrame:CGRectMake(0, -20, WIDTH, 20)];
//    _label.backgroundColor = [UIColor colorWithRed:236/255.0 green:236/255.0 blue:236/255.0 alpha:1];
//    _label.text = @"          最近更新";
//    UIView *kuai = [[UIView alloc] initWithFrame:CGRectMake(5, 5, 5, 10)];
//    kuai.backgroundColor = [UIColor redColor];
//    [_label addSubview:kuai];
    
    [self.view addSubview:_collectionView];
    [self.collectionView addSubview:_label];
    __block __typeof(&*self)ws = self;
    [_collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(ws.view.mas_left).with.offset(0);
        make.right.equalTo(ws.view.mas_right).with.offset(0);
        make.top.equalTo(ws.view.mas_top).with.offset(0);
        make.bottom.equalTo(ws.view.mas_bottom).with.offset(0);
    }];
    [layout release];
    [_collectionView release];
}
#pragma maek -data
- (void)data
{
    //AFN网络请求
    AFHTTPSessionManager *data = [AFHTTPSessionManager manager];
    [data GET:_urlStr parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        nil;
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSArray *arr = responseObject[@"result"];
        self.next = responseObject[@"next"];
        self.dataArr = [WMEArticleModel modelHandlerWithArray:arr];
        [_collectionView reloadData];
        if (_next.integerValue != 0) {
            [self loadingFunction];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        nil;
    }];

}
- (void)createView
{
    self.label = [[UILabel alloc] initWithFrame:CGRectMake(0, -20, WIDTH, 20)];
    _label.backgroundColor = [UIColor colorWithRed:236/255.0 green:236/255.0 blue:236/255.0 alpha:1];
    [self.view addSubview:_label];
    _label.text = @"     最近更新";
    UIView *kuai = [[UIView alloc] initWithFrame:CGRectMake(5, 5, 2, 10)];
    kuai.backgroundColor = [UIColor redColor];
    [_label addSubview:kuai];
}
#pragma mark -collectionView的协议方法
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (_dataArr.count != 0) {
        return _dataArr.count;
    }
    return 0;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    [_collectionView registerClass:[WMEArticleFirstCollectionViewCell class] forCellWithReuseIdentifier:@"articieFirstCell"];
    WMEArticleFirstCollectionViewCell *articieFirst = [_collectionView dequeueReusableCellWithReuseIdentifier:@"articieFirstCell" forIndexPath:indexPath];
    if (_dataArr.count != 0) {
        WMEArticleModel *model = _dataArr[indexPath.item];
        articieFirst.model = model;
    }
    return articieFirst;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (_dataArr.count != 0) {
        WMEArticleModel *model = _dataArr[indexPath.item];
        WMEArticleInformationViewController *articleInformation = [[WMEArticleInformationViewController alloc] init];
        articleInformation.model = model;
        [self.navigationController pushViewController:articleInformation animated:YES];
    }
}

#pragma mark - 刷新
- (void)refreshFunction
{
    _collectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [_dataArr removeAllObjects];
        [self data];
        [_collectionView.mj_header endRefreshing];
    }];
}
#pragma mark - 加载
- (void)loadingFunction
{
    _collectionView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        NSString *newUrl = [NSString stringWithFormat:@"%@%@",_urlStr, _next];
        AFHTTPSessionManager *data = [AFHTTPSessionManager manager];
        [data GET:newUrl parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
            nil;
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            NSArray *arr = responseObject[@"result"];
            self.next = responseObject[@"next"];
            NSArray *tempArr = [WMEArticleModel modelHandlerWithArray:arr];
            [_dataArr addObjectsFromArray:tempArr];
            [_collectionView reloadData];
            if (_next.integerValue  == 0) {
                [_collectionView.mj_footer endRefreshingWithNoMoreData];
            }else{
                [_collectionView.mj_footer endRefreshing];
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            nil;
        }];
    }];
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
